package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.user.IUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.ApCommentRepayNew;
import com.heima.comment.service.BaiduScanService;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.comment.dtos.CommentRepayDto;
import com.heima.model.common.comment.dtos.CommentRepayLikeDto;
import com.heima.model.common.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl  implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private BaiduScanService baiduScanService;
    @Autowired
    private IUserClient userClient;

    /**
     * 点赞
     *
     * @param commentRepayLikeDto
     * @return
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto commentRepayLikeDto) {
        //1.校验参数
        if (commentRepayLikeDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.登录用户
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.增加点赞
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentRepayLikeDto.getCommentRepayId())), ApCommentRepay.class);
        if (apCommentRepay != null && commentRepayLikeDto.getOperation() == 0){
            //增加点赞数
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            //记录当前用户对于当前评论的数据记录
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(commentRepayLikeDto.getCommentRepayId());
            apCommentRepayLike.setAuthorId(userId);
            mongoTemplate.save(apCommentRepayLike);
        }else {
            //取消点赞
            Integer likes = apCommentRepay.getLikes();
           if (likes - 1 < 0){
               apCommentRepay.setLikes(0);
           }else {
               apCommentRepay.setLikes( apCommentRepay.getLikes() - 1 );
           }
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(commentRepayLikeDto.getCommentRepayId());
            apCommentRepayLike.setAuthorId(userId);
            mongoTemplate.save(apCommentRepayLike);
        }
        return ResponseResult.okResult(apCommentRepay.getLikes());
    }

    /**
     * 查询评论回复列表
     *
     * @param commentRepayDto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto commentRepayDto) {
        //1.校验参数
        if (commentRepayDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.设置分页查询的默认10数据
        commentRepayDto.setSize(10);

        //3.展示评论回复的列表，按时间倒叙排序
        Query query = Query.query(Criteria.where("commentId")
                .is(commentRepayDto.getCommentId())
                .and("createdTime")
                .lt(commentRepayDto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(commentRepayDto.getSize());
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);

        //4.判断用户登录
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //5.查看哪些评论是被点赞的,并且是当前用户所点赞的
        //5.1查出所有的id
        List<String> AllIdList  = apCommentRepays.stream().map(apCommentRepay -> apCommentRepay.getId()).collect(Collectors.toList());
        //5.2查出所有作者所点赞的id
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(AllIdList).and("authorId").is(userId)), ApCommentRepayLike.class);
        //5.3如果没有点赞的话，直接返回
        if (apCommentRepayLikes == null || apCommentRepayLikes.size() == 0){
            return ResponseResult.okResult(apCommentRepays);
        }
        //6.如果有点赞的话设置operation。apCommentRepays的id等于apCommentRepayLike的评论id
        List<ApCommentRepayNew> apCommentRepayNewList = new ArrayList<>();
        apCommentRepays.forEach(
               apCommentRepay -> {
                   ApCommentRepayNew apCommentRepayNew = new ApCommentRepayNew();
                   BeanUtils.copyProperties(apCommentRepay,apCommentRepayNew);
                   for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                        if (apCommentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())){
                            apCommentRepayNew.setOperation(0);
                            //如果查到有点赞的话，需要加载进NewList，要跳出循环标记上有点赞
                            break;
                        }
                   }
                   apCommentRepayNewList.add(apCommentRepayNew);
               }
        );
        return ResponseResult.okResult(apCommentRepayNewList);
    }

    /**
     * 保存
     *
     * @param commentRepaySaveDto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentRepaySaveDto commentRepaySaveDto) {
        //1.校验参数
        if (commentRepaySaveDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.登录人
        //3.1.判断是否登录
        Integer userId = ApThreadLocalUtil.get();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.2评论内容不能超过140字
        if (commentRepaySaveDto.getContent().length() > 140){
            throw new CustomException(AppHttpCodeEnum.TOO_MANY_WORDS);
        }
        //3.3文本检测
        Integer textId = baiduScanService.scanText(commentRepaySaveDto.getContent());
        if (textId != 1){
            throw new CustomException(AppHttpCodeEnum.VIOLATING_TEXT);
        }
        //4.根据作者保存
        ApUser user = userClient.getUser(userId);
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(userId);
        apCommentRepay.setAuthorName(user.getName());
        BeanUtils.copyProperties(commentRepaySaveDto,apCommentRepay);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        //保存
        mongoTemplate.save(apCommentRepay);

        //5.更新评论的回复数量
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentRepaySaveDto.getCommentId())), ApComment.class);
        if (apComment == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
